package com.bawei.service;

import com.bawei.dao.UserRepository;
import com.bawei.entity.Area;
import com.bawei.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override/*分页列表*/
    public Page<User> list(Integer current, Integer size, User user,String username) {
        Specification specification=new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder cb) {
                List<Predicate> predicates=new ArrayList<>();
                if(!StringUtils.isEmpty(username)){
                    predicates.add(cb.like(root.get("username"),"%".concat(username).concat("%")));
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        Pageable of=PageRequest.of(current-1,size);
        return userRepository.findAll(specification,of);
    }

    @Override/*添加或修改*/
    public void save(User user) {
        userRepository.save(user);
    }

    @Override/*删除或批量删除*/
    public void delete(Integer[] ids) {
        for (int i=0;i<ids.length;i++) {
            userRepository.deleteById(ids[i]);
        }
    }
}
